
import * as Cesium from 'cesium';

const getObj = (str: string) => {
    //判断转换后的值是否还是字符串，直到返回的不是字符串为止
    if (typeof str === 'string') {
        return getObj(JSON.parse(str));
    } else {
        return str;
    }
}


export const setTilsesetStyle = (tileset: Cesium.Cesium3DTileset, data: any) => {
    const { ElementID, UUID } = data as { ElementID: number, UUID: string };

    //earthds 要素类字段配置 _ds
    // const val = feature.getProperty('_ds');
    // "{\"ElementID\":1445774,\"UUID\":\"3808d29f37f04468b90b91811c0496ac00160f8e\"}"
    //JSON.parse(JSON.parse(val))当前版本需要转换，后续版本按具体值来修改

    const evaluateColor = (feature: Cesium.Cesium3DTileFeature, result: Cesium.Color | undefined) => {
        try {
            const val = feature.getProperty('_ds');
            const tile = getObj(val) as { ElementID: number, UUID: string };
            if (ElementID === tile.ElementID) {
                return Cesium.Color.fromCssColorString('red', result);//条件着色
            } else {
                return Cesium.Color.clone(Cesium.Color.WHITE, result);
            }
        } catch (error) {
            // console.warn(error);
            return Cesium.Color.clone(Cesium.Color.WHITE, result);
        }
    };

    const evaluateShow = (feature: Cesium.Cesium3DTileFeature) => {
        try {
            const val = feature.getProperty('_ds');
            const tile = getObj(val) as { ElementID: number, UUID: string };
            if (ElementID !== tile.ElementID) {
                return true;//根据条件判断是否显示
            } else {
                return true;
            }
        } catch (error) {
            // console.warn(error);
            return true;
        }
    }

    const style = new Cesium.Cesium3DTileStyle({
        color: {
            evaluateColor: function (feature: Cesium.Cesium3DTileFeature, result?: Cesium.Color) {
                return evaluateColor(feature, result);
            },
        },
        show: {
            evaluate: function (feature: Cesium.Cesium3DTileFeature) {
                return evaluateShow(feature);
            },
        },
    });

    tileset.style = style;
}
